<template>
  <div>
    <!--进出口信息-->
    <TypeTitle :title="$t('IMPORT_EXPORT_INFORMATION')" />
    <!--进口信息-->
    <div class="flex align-center justify-between mb-10">
      <span class="label-text ml-10">{{ $t("IMPORT_INFORMATION") }}：</span>
      <div>
        <span>{{ $t("IMPORT_QUANTITY") }}：{{ inputList.length }}</span>
      </div>
    </div>
    <el-table :data="inputList" border max-height="200px" style="width: 100%">
      <el-table-column
        type="index"
        :label="$t('SEQUENCE')"
        :width="resetSize(100)"
        align="center"
      />
      <el-table-column prop="spliceName" :label="$t('IMPORT_NAME')">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.spliceName"
            :readonly="scope.row.read"
            :placeholder="`${$t('PLEASE_INPUT')}${$t('IMPORT_NAME')}`"
            @input="inputChange($event, scope.$index, 'name')"
          />
        </template>
      </el-table-column>
      <el-table-column prop="number" :label="$t('IMPORTED_FIBER_CORES')">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.number"
            :readonly="scope.row.read"
            :placeholder="`${$t('PLEASE_INPUT')}${$t('IMPORTED_FIBER_CORES')}`"
            onkeyup="value=value.replace(/\D/g,'')"
            @input="inputChange($event, scope.$index, 'number')"
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('OPERATE')" class-name="operate-cell" width="80">
        <template v-slot="scope">
          <i
            v-if="scope.$index === spliceClosure.inputList.length - 1"
            class="el-icon-plus mr-10 icon-font"
            @click="changeImportNum('add')"
          />
          <i
            v-if="spliceClosure.inputList.length > 1 && !scope.row.read"
            class="el-icon-minus icon-font"
            @click="changeImportNum('minus', scope.$index, scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!--出口信息-->
    <div class="flex align-center justify-between mb-10 mt-10">
      <span class="label-text ml-10">{{ $t("EXPORT_INFORMATION") }}：</span>
      <div>
        <span>{{ $t("EXPORT_VOLUME") }}：{{ outputList.length }}</span>
      </div>
    </div>
    <el-table
      :data="outputList"
      border
      max-height="200px"
      style="width: 100%; margin-bottom: 40px"
    >
      <el-table-column
        type="index"
        :label="$t('SEQUENCE')"
        :width="resetSize(100)"
        align="center"
      />
      <el-table-column prop="spliceName" :label="$t('EXPORT_NAME')">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.spliceName"
            :readonly="scope.row.read"
            :placeholder="`${$t('PLEASE_INPUT')}${$t('EXPORT_NAME')}`"
            @input="outputChange($event, scope.$index, 'name')"
          />
        </template>
      </el-table-column>
      <el-table-column prop="number" :label="$t('EXPORTED_FIBER_CORES')">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.number"
            :readonly="scope.row.read"
            :placeholder="`${$t('PLEASE_INPUT')}${$t('EXPORTED_FIBER_CORES')}`"
            onkeyup="value=value.replace(/\D/g,'')"
            @input="outputChange($event, scope.$index, 'number')"
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('OPERATE')" class-name="operate-cell" width="80">
        <template v-slot="scope">
          <i
            v-if="scope.$index === spliceClosure.outputList.length - 1"
            class="el-icon-plus mr-10 icon-font"
            @click="changeExportNum('add')"
          />
          <i
            v-if="spliceClosure.outputList.length > 1 && !scope.row.read"
            class="el-icon-minus icon-font"
            @click="changeExportNum('minus', scope.$index, scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!--端口配置-->
    <TypeTitle :title="$t('PORT_CONFIGURATION')">
      <el-popover width="200" trigger="hover">
        <div class="text-color" v-html="$t('DIVERGENCEPORT_TIPS')" />
        <i
          slot="reference"
          class="iconfont icon-AFSwenhao text-color ml-5 font-weight-normal"
        />
      </el-popover>
    </TypeTitle>
    <!--批量操作-->
    <div class="flex align-center justify-end mb-10">
      <el-button type="primary" :disabled="clearDisabled" @click="clearClick">{{
        $t("ONECLICK_CLEAR")
      }}</el-button>
      <el-button
        slot="trigger"
        class="ml-10"
        size="mini"
        type="primary"
        :disabled="clearDisabled"
        @click="importVisible = true"
      >{{ $t("IMPORT") }}</el-button>
      <el-button type="primary" :disabled="clearDisabled" @click="autoVisible = true">{{
        $t("AUTO_GENERATE")
      }}</el-button>
    </div>
    <!--端口表格列表-->
    <PortConfig
      ref="PortConfig"
      select-id="selectDivDivergencePort"
      :type="type"
      :splice-closure="spliceClosure"
    />

    <!--端口配置-自动生成-->
    <el-dialog
      title="PORTCONFIGURATION_AUTOGENERATE"
      :visible.sync="autoVisible"
      append-to-body
      width="1000px"
    >
      <!--端口表格列表-->
      <PortConfig
        ref="autoPortConfig"
        type="auto"
        select-id="selectPortConfig"
        :splice-closure="spliceClosure"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="autoVisible = false">取 消</el-button>
        <el-button type="primary" @click="autoConfirmFn">确 定</el-button>
      </span>
    </el-dialog>

    <!--导入引导-->
    <import-boot
      :visible="importVisible"
      @ImportClick="importClick"
      @import-close="importVisible = false"
    >
      <template #notice>
        {{ $t("BEFORE_IMPORTING_PLEASE") }}
        <span class="exportClick" @click="exportClick">
          {{ $t("EXPORT_TEMPLATE") }}
        </span>
        {{ $t("ALL_PORT_INFORMATION") }}
      </template>
    </import-boot>
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  import { importExcel, exportExcel } from '@/utils/jsonToExcel'
  import { generateUuid, deepClone } from '@/utils/common'
  import TypeTitle from '@/components/TypeTitle.vue'
  import PortConfig from './PortConfig.vue'
  import NodeApi from '@/api/oen/NodeApi'
  import OperateLogApi from '@/api/system/OperateLogApi.js'
  import ImportBoot from '@/components/ImportBoot'
  export default {
    name: 'Divergence',
    components: { TypeTitle, PortConfig, ImportBoot },
    props: {
      rowData: {
        type: Object,
        default: () => {}
      },
      deviceProp: {
        type: Object,
        default: () => {}
      },
      type: {
        type: String,
        default: 'add'
      }
    },
    data() {
      return {
        showSelect: false,
        activeCurVal: {
          selectVal: ''
        },
        activeList: [], // 当前点击选中的列表
        autoVisible: false,
        portListStatus: [],
        clearDisabled: false,
        importVisible: false
      }
    },
    computed: {
      ...mapGetters(['getUserId', 'getUser']),
      spliceClosure() {
        return this.deviceProp.spliceClosure
      },
      inputList() {
        return this.spliceClosure.inputList
      },
      outputList() {
        return this.spliceClosure.outputList
      }
    },
    created() {
      if (this.type === 'mod') {
        this.portList()
      }
    },
    methods: {
      portList() {
        // 获取节点下的端口列表状态
        const list = deepClone(this.spliceClosure.splicePortInfoList)
        const inputIds = list.map((i) => i.inputSplicePortId)
        const outputIds = list.map((i) => i.outputSplicePortId)
        NodeApi.portList({
          nodeId: this.rowData.nodeId,
          portIds: [...inputIds, ...outputIds]
        }).then((res) => {
          this.portListStatus = res || []
          // 把端口状态赋值给进出端口列表项
          list.forEach((item) => {
            const inputObj = this.portListStatus.find(
              (port) => item.inputSplicePortId === port.portId
            )
            const outputObj = this.portListStatus.find(
              (port) => item.outputSplicePortId === port.portId
            )
            const isDisabled =
              inputObj &&
              inputObj.status === 'IDLE' &&
              outputObj &&
              outputObj.status === 'IDLE'
            item.inputStatus = isDisabled ? 'IDLE' : 'conne'
            item.outputStatus = isDisabled ? 'IDLE' : 'conne'
          })
          // console.log('list-------', list)
          this.spliceClosure.splicePortInfoList = list
          this.$refs.PortConfig.initSplicePortInfoList('mod')
          // 获取当前进出口端口是否有被占用的， 如果有就不能修改进出口信息
          const inputids = list
            .filter((i) => i.inputStatus !== 'IDLE')
            .map((j) => j.inputSpliceId)
          this.clearDisabled = false
          this.inputList.forEach((item, index) => {
            if (inputids.includes(item.spliceId)) {
              this.clearDisabled = true
              this.$set(this.inputList, index, { ...item, read: true })
            }
          })
          const outputids = list
            .filter((i) => i.outputStatus !== 'IDLE')
            .map((j) => j.outputSpliceId)
          this.outputList.forEach((item, index) => {
            if (outputids.includes(item.spliceId)) {
              this.clearDisabled = true
              this.$set(this.outputList, index, { ...item, read: true })
            }
          })
        })
      },
      autoConfirmFn() {
        // 自动生成确认 生成列表
        const list = this.$refs.autoPortConfig.splicePortInfoList
        // console.log(list)
        if (
          list.some(
            (i) =>
              !i.inputSpliceId ||
              !i.inputSplicePortName ||
              !i.outputSpliceId ||
              !i.outputSplicePortName ||
              !i.portNumber
          )
        ) {
          this.$message.error(this.$t('CONFIGURATION_INFORMATION'))
          return
        }
        this.$confirm(this.$t('AUTOMATIC_GENERATION_TIPS'), { type: 'warning' })
          .then(() => {
            const arr = []
            list.forEach((item) => {
              const strInNum = item.inputSplicePortName.lastIndexOf('-') + 1
              const strOutNum = item.outputSplicePortName.lastIndexOf('-') + 1
              let inputNum = Number(item.inputSplicePortName.slice(strInNum))
              let outputNum = Number(item.outputSplicePortName.slice(strOutNum))
              const maxPortNum = Math.max(inputNum, outputNum)
              const minNum = Math.min(item.inputNumber, item.outputNumber, item.portNumber)
              const totalNum = minNum - maxPortNum
              let i = 0
              while (i <= totalNum) {
                arr.push({
                  inputSpliceId: item.inputSpliceId,
                  inputSplicePortName: item.inputName + '-' + inputNum,
                  outputSpliceId: item.outputSpliceId,
                  outputSplicePortName: item.outputName + '-' + outputNum
                })
                i++
                inputNum++
                outputNum++
              }
            })
            // console.log(arr)
            this.spliceClosure.splicePortInfoList = arr
            // 更新端口配置列表
            this.$nextTick(() => {
              this.$refs.PortConfig.initSplicePortInfoList('mod')
              this.autoVisible = false
            })
          })
          .catch(() => {})
      },
      inputChange(val, index, type) {
        // 进口信息改变后端口配置进口名称修改
        this.$refs.PortConfig.inputChange(val, index, type)
      },
      outputChange(val, index, type) {
        // 出口信息改变后端口配置进口名称修改
        this.$refs.PortConfig.outputChange(val, index, type)
      },
      changeImportNum(type, index, row) {
        // 进口增加
        if (type === 'add') {
          this.inputList.push({
            spliceId: generateUuid(),
            spliceName: '',
            number: ''
          })
          return
        }
        // 删除进口 端口列表相关信息也要删除
        const list = this.spliceClosure.splicePortInfoList
        this.spliceClosure.splicePortInfoList = list.filter(
          (i) => i.inputSpliceId !== row.spliceId
        )
        this.$refs.PortConfig.initSplicePortInfoList('mod')
        this.inputList.splice(index, 1)
      },
      changeExportNum(type, index, row) {
        // 出口增加
        if (type === 'add') {
          this.outputList.push({
            spliceId: generateUuid(),
            spliceName: '',
            number: ''
          })
          return
        }
        // 删除出口 端口列表相关信息也要删除
        const list = this.spliceClosure.splicePortInfoList
        this.spliceClosure.splicePortInfoList = list.filter(
          (i) => i.outputSpliceId !== row.spliceId
        )
        this.$refs.PortConfig.initSplicePortInfoList('mod')
        this.outputList.splice(index, 1)
      },
      getSplicePortInfoList() {
        return this.$refs.PortConfig.splicePortInfoList
      },
      clearClick() {
        // 一键清空
        this.$confirm(this.$t('ONE_CLICK_CLEARING'), {
          type: 'warning'
        })
          .then(() => {
            this.spliceClosure.splicePortInfoList = [
              {
                inputSpliceId: '',
                inputSplicePortName: '',
                outputSpliceId: '',
                outputSplicePortName: ''
              }
            ]
            this.$refs.PortConfig.initSplicePortInfoList('add')
          })
          .catch(() => {})
      },
      // 导入
      importClick(file) {
        importExcel(file).then((res) => {
          console.log(res)
          if (file.name.includes(this.rowData.nodeName)) {
            this.importData(res.data)
          } else {
            this.$message.error(
              `${this.$t('PLEASE_UPLOAD_NODE')}${this.rowData.nodeName}${this.$t(
                'TEMPLATE_FILE'
              )}`
            )
          }
        })
      },
      importData(data) {
        const list = []
        data.forEach((item, index) => {
          const obj = {}
          const values = Object.values(item)
          for (const value of values) {
            this.inputList.forEach((i) => {
              if (value === i.spliceName) {
                obj.inputSpliceId = i.spliceId
                obj.inputSplicePortName = values[1]
              }
            })
            this.outputList.forEach((i) => {
              if (value === i.spliceName) {
                obj.outputSpliceId = i.spliceId
                obj.outputSplicePortName = values[3]
              }
            })
          }
          list.push(obj)
        })
        this.spliceClosure.splicePortInfoList = list
        this.$refs.PortConfig.initSplicePortInfoList('mod')
        this.importVisible = false
      },
      // 导出文件
      exportClick() {
        try {
          const sheets = [
            [
              [
                this.$t('IMPORT_NAME'),
                this.$t('IMPORT_PORT_NUMBER'),
                this.$t('EXPORT_NAME'),
                this.$t('EXPORT_PORT_NUMBER')
              ],
              ['进口1', '进口1-1', '出口1', '出口1-1']
            ]
          ]
          const sheetNames = [`${this.rowData.nodeName}端口列表`]
          const merge = [{ s: { r: 0, c: 0 }, e: { r: 0, c: 0 }}]
          exportExcel(
            sheets,
            `${this.rowData.nodeName}${this.$t('FEATURE_TYPE_NODE')}${this.$t(
              'PORT_EXPORT'
            )}`,
            sheetNames,
            'array',
            merge
          )
          // 记录导出日志
          this.addLog({
            api: '/',
            terminal: 'EDIT_PORT_EXPORT', // 导出
            object: this.rowData.nodeName,
            i18nKey: 'EDIT_PORT_EXPORT_LOG',
            deviceName: this.rowData.nodeName,
            operateResult: true
          })
        } catch (error) {
          console.log(error)
          // 记录导出日志
          this.addLog({
            api: '/',
            terminal: 'EDIT_PORT_EXPORT', // 导出
            object: this.rowData.nodeName,
            i18nKey: 'EDIT_PORT_EXPORT_LOG',
            deviceName: this.rowData.nodeName,
            operateResult: false
          })
        }
      },
      addLog(logData) {
        const obj = {
          ...logData,
          item: 'MENU_NODE_MANAGER', // 节点管理
          realName: this.getUser.realName,
          content: JSON.stringify({
            deviceName: logData.deviceName,
            currentUserId: this.getUserId,
            i18nKey: logData.i18nKey
          })
        }
        // 记录导出日志
        OperateLogApi.addLog(obj)
      }
    }
  }
</script>
<style lang="scss" scoped>
.label-text {
  position: relative;
  text-align: center;
}
.label-text:before {
  content: "*";
  color: #f56c6c;
  position: absolute;
  transform: translateY(5px) translateX(-5px);
}
</style>
